<template>
  <div>
    <el-button @click="print" :loading="loading" type="primary">开始打印</el-button>
    <el-input v-model="pdfNum" style="width: 200px;"></el-input>
    <div v-if="printShow" id="playerDetailPrint" style="width: 600px;padding:50px 50px 50px 50px;overflow: visible;">
      <weekAndClassPlanPrintAuto v-if="currentDocClassId==33||currentDocClassId==34" id="myPrint" :previewData="printData"
        :docClassId="currentDocClassId" />
      <otherPlanPrint v-else id="myPrint" :previewData="printData" :docClassId="currentDocClassId" />
    </div>
  </div>
</template>

<script>
  import html2Canvas from 'html2canvas'
  import JsPDF from 'jspdf'
  // import VueHtml2pdf from 'vue-html2pdf'
  import {
    plan_doc_all,
    allType,
    plan_doc_select
  } from '@/api/plan.js'
  import {
    sport_by_org,
    currentRoleEmployee,
    plan_doc_available
  } from '@/api/dict.js'
  import otherPlanPrint from "@/components/print/otherPlanPrint.vue"
  import weekAndClassPlanPrintAuto from "@/components/print/weekAndClassPlanPrintAuto.vue"
  export default {
    components: {
      otherPlanPrint,
      weekAndClassPlanPrintAuto,
    },
    data() {
      return {
        printData: {},
        defaultData: [],
        fileName: '',
        download: false,
        pdfSave: 1,
        pdfNum: 0,
        currentDocClassId: 0,
        dict_sport: {},
        dict_emp: {},
        nameArr: [],
        dict_docClass: {},
        loading: false,
        printShow: false,
      }
    },
    computed: {
      pdfOptions() {
        return {
          margin: [0, 5, 0, 5],
          pagebreak: {
            mode: 'avoid-all'
          }
        }
      },
    },
    created() {
      this.init_dict()
    },
    watch: {},
    methods: {
      init_dict() {
        this.loading = true
        return new Promise((resolve, reject) => {
          plan_doc_available().then(res=>{
            this.dict_docClass = res
          }).then(()=>{
            sport_by_org().then(res => {
              this.dict_sport = res
            }).then(() => {
              currentRoleEmployee().then(res => {
                this.dict_emp = res
              }).then(()=>{
                for(let key in this.dict_docClass){
                  if(key != 34){
                    plan_doc_select({data:{docClassId:key}}).then(res => {
                      if (res.code === 200 && res.data.length != 0) {
                        this.defaultData.push(...res.data)
                        this.loading = false
                        resolve()
                      }
                    })
                  }
                }
              })
            })
          })
        })
      },
      print() {
        if (this.defaultData.length == 0) {
          this.$message.error('没有数据怎么打印？！！！')
          return
        }
        if (this.pdfNum != this.defaultData.length) {
          this.playerDetailPrint(this.defaultData[this.pdfNum])
        }
      },
      playerDetailPrint(item) {
        let data = {
          docDataId: item.docDataId,
          docClassId: item.docClassId,
        }
        this.currentDocClassId = item.docClassId
        allType(data).then(res => {
          if (res.code === 200) {
            this.printData = res.data
            this.printShow = true
          }
        }).then(() => {
          let dom = document.getElementById('playerDetailPrint')
          let count = ''
          let planName = (this.dict_sport[item.sportId] || 'XXX') + '-' + (this.dict_emp[item.empId] || 'XXX') +
            '-' + item.name
          this.nameArr.push(planName)
          let num = 0
          this.nameArr.forEach(item => {
            if (item == planName) {
              num++
            }
          })
          count = (num).toString()
          if (count.length == 1) {
            count = '-00' + count
          } else if (count.length == 2) {
            count = '-0' + count
          } else {
            count = '-' + count
          }
          this.getPdfFromHtml(dom, planName + count)
        })
      },
      getPdfFromHtml(ele, pdfFileName) {
        html2Canvas(ele, {
          dpi: window.devicePixelRatio * 4,
          scale: 4,
          useCORS: true, //允许canvas画布内可以跨域请求外部链接图片, 允许跨域请求。
          allowTaint: false,
          height: ele.offsetHeight,
          width: ele.offsetWidth,
          windowWidth: document.body.scrollWidth,
          windowHeight: document.body.scrollHeight,
        }).then(canvas => {
          this.dialogVisible = true;
          const _this = this;
          //未生成pdf的html页面高度
          var leftHeight = canvas.height;
          var a4Width = 595.28
          var a4Height = 841.89
          //一页pdf显示html页面生成的canvas高度;
          var a4HeightRef = Math.floor(canvas.width / a4Width * a4Height);

          //pdf页面偏移
          var position = 0;

          var pageData = canvas.toDataURL('image/jpeg', 1.0);

          var pdf = new JsPDF('x', 'pt', 'a4');
          var index = 1,
            canvas1 = document.createElement('canvas'),
            height;
          pdf.setDisplayMode('fullwidth', 'continuous', 'FullScreen');

          // $('.head-content').append($(
          //   '<div class="pdfTip">' +
          //   '   <div>正在生成第<span class="pdfProgress">1</span>页，共<span class="pdfTotal"></span>页...' +
          //   '</div>'));
          function createImpl(canvas) {
            if (leftHeight > 0) {
              index++;
              var checkCount = 0;
              if (leftHeight > a4HeightRef) {
                var i = position + a4HeightRef;
                for (i = position + a4HeightRef; i >= position; i--) {
                  var isWrite = true
                  for (var j = 0; j < canvas.width; j++) {
                    var c = canvas.getContext('2d').getImageData(j, i, 1, 1).data

                    if (c[0] != 0xff || c[1] != 0xff || c[2] != 0xff) {
                      isWrite = false
                      break
                    }
                  }
                  if (isWrite) {
                    checkCount++
                    if (checkCount >= 10) {
                      break
                    }
                  } else {
                    checkCount = 0
                  }
                }
                height = Math.round(i - position) || Math.min(leftHeight, a4HeightRef);
                if (height <= 0) {
                  height = a4HeightRef;
                }
              } else {
                height = leftHeight;
              }

              canvas1.width = canvas.width;
              canvas1.height = height;

              // console.log(index, 'height:', height, 'pos', position);

              var ctx = canvas1.getContext('2d');
              ctx.drawImage(canvas, 0, position, canvas.width, height, 0, 0, canvas.width, height);

              var pageHeight = Math.round(a4Width / canvas.width * height);
              // pdf.setPageSize(null, pageHeight)
              if (position != 0) {
                pdf.addPage();
              }
              pdf.addImage(canvas1.toDataURL('image/jpeg', 1.0), 'JPEG', 0, 20, a4Width, a4Width / canvas1.width *
                height);
              leftHeight -= height;
              position += height;
              // $('.pdfProgress').text(index + 1);
              // $('.pdfTotal').text(index + Math.ceil(leftHeight / a4HeightRef));
              if (leftHeight > 0) {
                //添加全屏水印
                // const base64 = ''
                // for(let i=0;i<6;i++){
                //   for(let j=0;j<5;j++){
                //     const  left = (j*120)+20;
                //     pdf.addImage(base64,'JPEG', left, i*150, 20, 30);
                //   }
                // }
                setTimeout(createImpl, 500, canvas);
              } else {
                // _this.iframeSrc = pdf.output('dataurlstring');
                // debugger;
                this.pdfSave = pdf.save(pdfFileName + '.pdf');
              }
            }
          }

          //当内容未超过pdf一页显示的范围，无需分页
          if (leftHeight < a4HeightRef) {
            pdf.addImage(pageData, 'JPEG', 0, 0, a4Width, a4Width / canvas.width * leftHeight);
            this.dialogVisible = true;
            // this.iframeSrc = pdf.output('dataurlstring');
            // debugger;
            this.pdfSave = pdf.save(pdfFileName + '.pdf')
          } else {
            try {
              pdf.deletePage(0);
              // $('.pdfTip').show();
              // $('.pdfTotal').text(index + Math.ceil(leftHeight / a4HeightRef));
              setTimeout(createImpl, 500, canvas);

            } catch (err) {
              console.log(err);
            }
          }
        }).then(() => {
          this.printShow = false
          this.pdfNum = parseInt(this.pdfNum)
          this.pdfNum += 1
        }).then(() => {
          this.print()
        })

      },
    }
  }
</script>

<style scoped>

</style>
